package bili_live

import (
	"iptv_server/v3/v2_src/utils"
	"net/http"
)

func makeAgent(roomid int64) *serverState {
	return newServerState(roomid)
}

func getRandom(roomid int64, n int) (url string) {
	agent := makeAgent(roomid)
	if agent == nil {
		return ""
	}
	all, seq := agent.getVideoUrls()
	var key string
	var ok bool
	if n < 0 {
		key, ok = utils.GetRandomFromSlice(seq)
		if !ok {
			return ""
		}
	} else {
		if len(seq) <= n {
			return ""
		} else {
			key = seq[n]
		}
	}

	if url, ok := all[key]; ok {
		return url
	}
	return ""
}

// GetAll(833792)
func GetAll(roomid int64) map[string]string {
	agent := makeAgent(roomid)
	if agent == nil {
		return nil
	}

	all, _ := agent.getVideoUrls()
	return all
}

func GetRandom(roomid int64) (url string) {
	return getRandom(roomid, -1)
}

func GetFirst(roomid int64) (url string) {
	return getRandom(roomid, 0)
}

// var (
// 	round int
// )

func GetOne(roomid int64) (url string) {
	// defer func() {
	// 	round++
	// }()
	all := GetAll(roomid)
	length := len(all)
	i := 0
	for key, url := range all {
		// map 是随机顺序
		if check(key, url, i, length) {
			return url
		}
		i++
	}

	if len(all) > 0 {
		// fallback: 随机获取一个
		for _, v := range all {
			return v
		}
	}

	return ""

	// url = GetFirst(roomid)

	// if round%2 == 0 {
	// 	return GetFirst(roomid)
	// } else {
	// 	return GetRandom(roomid)
	// }

}

func check(key, url string, index, length int) bool {
	req, err := http.NewRequest(http.MethodGet, url, nil)
	if err != nil {
		return false
	}
	// req.Header.Add("User-Agent", utils.UA)
	// req.Header.Add("Referer", "https://www.bilibili.com")
	cl := http.Client{}
	resp, err := cl.Do(req)
	if err != nil {
		utils.Logger.Infof("%d/%d, bili check url failed,key=%v url=%v,err=%v", index, length, key, url, err)
		return false
	}
	defer resp.Body.Close()

	utils.Logger.Infof("%d/%d, bili check url code=%d, key=%v, url=%v", index, length, resp.StatusCode, key, url)
	return resp.StatusCode < 400

}
